package com.sunchangming.rpcgen;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class NameSpaceConverter implements Converter {

	@SuppressWarnings("rawtypes")
	@Override
	public boolean canConvert(Class clazz) {
		return clazz.equals(NameSpace.class);
	}

	@Override
	public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		final NameSpace ns = new NameSpace();
		ns.name = reader.getAttribute("name");
		if (ns.name == null || ns.name.isEmpty())
			throw new ConversionException("namespace节点必须具有name属性");

		String str = reader.getAttribute("max");
		if (str != null && !str.isEmpty())
			ns.max = Integer.valueOf(str);
		str = reader.getAttribute("min");
		if (str != null && !str.isEmpty())
			ns.min = Integer.valueOf(str);

		while (reader.hasMoreChildren()) {
			reader.moveDown();
			try {
				if ("namespace".equals(reader.getNodeName())) {
					final NameSpace ns1 = (NameSpace) context.convertAnother(ns, NameSpace.class);
					ns1.parent = ns;
					ns.childs.add(ns1);
				} else if ("bean".equals(reader.getNodeName())) {
					final Bean b = (Bean) context.convertAnother(ns, Bean.class);
					b.parent = ns;
					ns.beans.add(b);
				} else if ("enum".equals(reader.getNodeName())) {
					final Enum b = (Enum) context.convertAnother(ns, Enum.class);
					b.parent = ns;
					ns.enums.add(b);
				} else
					throw new ConversionException("不认识的节点" + reader.getNodeName());
			} finally {
				reader.moveUp();
			}
		}
		return ns;
	}

}
